<?php
/**
 * Created by PhpStorm.
 * User: User
 * Date: 8/30/14
 * Time: 9:00 AM
 */
namespace Apps\Frontend;
use Phalcon\Dispatcher,
    Phalcon\Mvc\View,
    Phalcon\Mvc\Dispatcher as MvcDispatcher,
    Phalcon\Events\Manager as EventsManager,
    Phalcon\Mvc\Dispatcher\Exception as DispatchException;
class Module
{
    public function registerAutoloaders(){
        $loader = new \Phalcon\Loader();
        $loader->registerNamespaces(array(
            'Apps\Frontend\Controllers' => APPLICATION_PATH.'/apps/frontend/controllers/',
            'Apps\Frontend\Models'      => APPLICATION_PATH.'/apps/frontend/models/',
            'Apps\Backend\Models'      => APPLICATION_PATH.'/apps/backend/models/',
            'Apps\Frontend\Forms'      => APPLICATION_PATH.'/apps/frontend/forms/',
        ));
        $loader->register();
    }
    public function registerServices($di)
    {
        $di->set('dispatcher', function () {
            //Create/Get an EventManager
            $eventsManager = new \Phalcon\Events\Manager();
            //Attach a listener
            $eventsManager->attach("dispatch", function ($event, $dispatcher, $exception) {
                //controller or action doesn't exist
                if ($event->getType() == 'beforeException') {
                    switch ($exception->getCode()) {
                        case \Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                        case \Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                            $dispatcher->forward(array(
                                'module'=>'frontend',
                                'controller' => 'index',
                                'action' => 'route404'
                            ));

                            return false;
                    }
                }
            });
            $dispatcher = new \Phalcon\Mvc\Dispatcher();
            $dispatcher->setDefaultNamespace("Apps\Frontend\Controllers");
            return $dispatcher;
        });
        $di->set('view', function() {
            $view = new View();
            $view->setViewsDir(APPLICATION_PATH.'/apps/frontend/views/');
            return $view;
        });
    }

}